package kd.hc.ecco;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.MulBasedataDynamicObjectCollection;
import kd.bos.entity.datamodel.RowDataEntity;
import kd.bos.entity.datamodel.events.AfterAddRowEventArgs;
import kd.bos.entity.datamodel.events.AfterDeleteRowEventArgs;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.property.EntryProp;
import kd.bos.form.CloseCallBack;
import kd.bos.form.ShowType;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.TreeEntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.hc.utils.BusinessDataServiceHelperExt;
import kd.hc.utils.ShowParameterUtil;
import kd.hc.utils.SourceBillToCurrentBill;
import kd.occ.ocbase.common.util.Convert;
import kd.sdk.plugin.Plugin;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 单据界面
 */
public class TargetCostUpdateBillPlugIn extends AbstractBillPlugIn implements Plugin, BeforeF7SelectListener {

    @Override
    public void initialize() {
        super.initialize();
    }

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        BasedataEdit travelbills = this.getView().getControl("hc95_cost_item_en");//目标成本项
        travelbills.addBeforeF7SelectListener(this);
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        FormOperate source = (FormOperate) e.getSource();
        String operateKey = source.getOperateKey();
        if ("deleteentry".equals(operateKey)) {
            TreeEntryGrid treeEntryGrid = this.getControl("hc95_tree_entryentity");
            int[] selectRows = treeEntryGrid.getSelectRows();
            DynamicObjectCollection hc95_tree_entryentity = this.getModel().getEntryEntity("hc95_tree_entryentity");
            String errorMsg = "";
            for (int selectRow : selectRows) {
                String hc95_oldmbcbmx_id = hc95_tree_entryentity.get(selectRow).getString("hc95_oldmbcbmx_id");
                if (StringUtils.isNotBlank(hc95_oldmbcbmx_id)) {
                    errorMsg = errorMsg + "第" + (selectRow + 1) + "行来源目标成本不允许删除!\n";
                }
            }
            if (errorMsg.length() >= 1) {
                e.setCancel(true);
                e.setCancelMessage(errorMsg);
                this.getView().showErrorNotification(errorMsg);
            }
        } else if ("insertentry".equals(operateKey)) {
            TreeEntryGrid treeEntryGrid = this.getControl("hc95_tree_entryentity");
        }
        super.beforeDoOperation(e);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent beforeF7SelectEvent) {
        String costItemKey = "hc95_cost_item_en";
        String propertyName = beforeF7SelectEvent.getProperty().getName();
        int row = beforeF7SelectEvent.getRow();
        if (StringUtils.equals(costItemKey, propertyName)) {
            ListShowParameter showParameter = (ListShowParameter) beforeF7SelectEvent.getFormShowParameter();
            DynamicObject entryentityRow = this.getModel().getEntryRowEntity("hc95_tree_entryentity", row);
            Object pkValue = entryentityRow.getPkValue();
            Long pid = entryentityRow.getLong("pid");
            List<QFilter> allFilters = new ArrayList<QFilter>();
            if (pid != null && pid > 0) {
                DynamicObject dynamicObject = this.getModel().getEntryEntity("hc95_tree_entryentity").stream().filter(i -> i.getString("id").equals(pid + "")).findFirst().get();
                DynamicObject parentItem = dynamicObject.getDynamicObject(costItemKey);
                if (parentItem == null) {
                    this.getView().showMessage("请先选中父节点目标成本项!");
                    beforeF7SelectEvent.setCancel(true);
                    return;
                }
                int levelSub = parentItem.getInt("level") + 1;
                String parent = parentItem.getString("id");
                QFilter qFilter = new QFilter("level", QCP.equals, levelSub);
                QFilter qFilter2 = new QFilter("parent.id", QCP.equals, parent);
                allFilters.add(qFilter);
                allFilters.add(qFilter2);
            } else {
                QFilter qFilter = new QFilter("level", QCP.equals, "1");
                allFilters.add(qFilter);
            }
            showParameter.getListFilterParameter().setQFilters(allFilters);
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        Map<String, Object> customParams = this.getView().getFormShowParameter().getCustomParams();
        if (customParams != null && customParams.size() >= 1) {
            if (customParams.containsKey("pk") && customParams.containsKey("sourceBill")) {
                Object pk = customParams.get("pk");
                String sourceBill = customParams.get("sourceBill") == null ? "" : customParams.get("sourceBill").toString();
                Boolean isExitPk = (Boolean) customParams.getOrDefault("isExitPk", false);
                isExitPk = isExitPk == null ? false : isExitPk;
                if (pk != null && "TargetCost".equals(sourceBill) && !isExitPk) {
                    List<String> selectEntryIds = customParams.get("selectEntryIds") == null ? new ArrayList<String>() : (List<String>) customParams.get("selectEntryIds");
                    this.getModel().setValue("hc95_mbcbd_id", pk);
                    // 开始 单据复制
                    DynamicObject targetCost = BusinessDataServiceHelper.loadSingle(pk, "hc95_target_cost");
                    Set<String> defaultIgnoreFields = SourceBillToCurrentBill.getDefaultIgnoreFields();
                    defaultIgnoreFields.add("billno");
                    SourceBillToCurrentBill.initSourceData(this.getView(), this.getModel(), targetCost, defaultIgnoreFields);
                    //变更单号
                    handVersionField();
                    //记录原数量 金额 税额 税率等相关字段
                    DynamicObjectCollection entryentity = this.getModel().getEntryEntity("hc95_tree_entryentity");
                    entryentity.forEach(item -> {
                        String hc95_oldmbcbmx_id = item.getString("hc95_oldmbcbmx_id");
                        item.set("hc95_ischange_en", false);
                        if (StringUtils.isNotBlank(hc95_oldmbcbmx_id) && selectEntryIds.contains(hc95_oldmbcbmx_id)) {
                            item.set("hc95_ischange_en", true);
                        }
                        item.set("hc95_price_en_x", item.get("hc95_price_en"));
                        item.set("hc95_qty_sum_en_x", item.get("hc95_qty_sum_en"));
                        item.set("hc95_ysmucbe_sum_en", item.get("hc95_zxmucbe_sum_en"));
                        item.set("hc95_change_amount_en", BigDecimal.ZERO);
                        item.set("hc95_sl_sum_en_x", item.get("hc95_sl_sum_en"));
                        item.set("hc95_se_sum_en_x", item.get("hc95_se_sum_en"));
                    });
                    this.getModel().updateEntryCache(entryentity);
                    this.getView().updateView("hc95_tree_entryentity");
                }
            }
        }
        //合计行
        onlyFiledLock();
        handleSumRow();
    }

    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {
        EntryProp entryProp = e.getEntryProp();
        String entryPropName = entryProp.getName();
        super.afterAddRow(e);
        if ("hc95_tree_entryentity".equals(entryPropName)) {
            RowDataEntity[] rowDataEntities = e.getRowDataEntities();
            if (rowDataEntities != null && rowDataEntities.length >= 1) {
                for (RowDataEntity rowDataEntity : rowDataEntities) {
                    int rowIndex = rowDataEntity.getRowIndex();
                    DynamicObject dataEntity = rowDataEntity.getDataEntity();
                    String id = dataEntity.getString("id");
                    String pid = dataEntity.getString("pid");
                    if ("0".equals(pid)) {
                        getModel().setValue("hc95_rank_en", 1, rowIndex);
                        getModel().setValue("hc95_longid_en", id, rowIndex);
                    } else {
                        DynamicObjectCollection targetCost = this.getModel().getEntryEntity("hc95_tree_entryentity");
                        DynamicObject parentRowData = targetCost.stream().filter(f1 -> f1.getString("id").equals(pid)).findFirst().get();
                        int rank = parentRowData.getInt("hc95_rank_en") + 1;
                        String longidEn = parentRowData.getString("hc95_longid_en");
                        longidEn = longidEn + "." + id;
                        getModel().setValue("hc95_rank_en", rank, rowIndex);
                        getModel().setValue("hc95_longid_en", longidEn, rowIndex);
                    }
                    getView().updateView("hc95_rank_en", rowIndex);
                    getView().updateView("hc95_longid_en", rowIndex);
                }
            }
            filedUpdateIsLeaf();
            handLeafAdd();
            treeSum();
            filedLock();
            handleSumRow();
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        OperationResult operationResult = e.getOperationResult();
        String operateKey = e.getOperateKey();
        if (operationResult != null) {
            boolean success = operationResult.isSuccess();
            if (success) {
                switch (operateKey) {
                    case "dofastaddline":
                        ShowParameterUtil.showFormShowParameter("新增成本类型", this.getView(), this.getModel(), "hc95_cost_type_autotree", ShowType.Modal, new CloseCallBack(this, operateKey));
                        break;
                }
            }
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        String actionId = closedCallBackEvent.getActionId();
        if (actionId.equals("dofastaddline")) {
            MulBasedataDynamicObjectCollection costType = (MulBasedataDynamicObjectCollection) closedCallBackEvent.getReturnData();
            if (costType != null && costType.size() >= 1) {
                // 把树形全部加载出来
                List<DynamicObject> allTreeCostType = new ArrayList<>();
                for (DynamicObject costTypeRow : costType) {
                    DynamicObject costTypeRowObject = costTypeRow.getDynamicObject("fbasedataid");
                    Object pkValue = costTypeRowObject.getPkValue();
                    costTypeRowObject = BusinessDataServiceHelperExt.loadSingle(pkValue, "hc95_costtype_tree");
                    iterationCostType(costTypeRowObject, allTreeCostType);
                }
                List<Integer> levels = allTreeCostType.stream().map(m1 -> m1.getInt("level")).collect(Collectors.toList());
                Integer levelMax = Collections.max(levels);
                DynamicObjectCollection entryentityColl = this.getModel().getEntryEntity("hc95_tree_entryentity");
                if (allTreeCostType.size() >= 1) {
                    for (int i = 1; i <= levelMax; i++) {
                        String finalI = i + "";
                        List<DynamicObject> level = allTreeCostType.stream().filter(f1 -> f1.getString("level").equals(finalI)).collect(Collectors.toList());
                        for (DynamicObject addRow : level) {
                            String currentCostTypeId = addRow.getPkValue().toString();
                            entryentityColl = this.getModel().getEntryEntity("hc95_tree_entryentity");
                            Optional<DynamicObject> firstCheck = entryentityColl.stream().filter(f1 -> f1.getString("hc95_cost_item_en.id").equals(currentCostTypeId)).findFirst();
                            if (!firstCheck.isPresent()) {//判断是否已经存在 已经存在跳过
                                if (i == 1) {
                                    int newRowIndex = this.getModel().createNewEntryRow("hc95_tree_entryentity");
                                    this.getModel().setValue("hc95_cost_item_en", addRow, newRowIndex);
                                } else {
                                    DynamicObject parent = addRow.getDynamicObject("parent");
                                    if (parent != null) {
                                        String parentCostTypeId = parent.getPkValue().toString();
                                        //找父级所在行号
                                        entryentityColl = this.getModel().getEntryEntity("hc95_tree_entryentity");
                                        Optional<DynamicObject> first = entryentityColl.stream().filter(f1 -> f1.getString("hc95_cost_item_en.id").equals(parentCostTypeId)).findFirst();
                                        if (first.isPresent()) {
                                            int newRowIndex = this.getModel().insertEntryRow("hc95_tree_entryentity", first.get().getInt("seq") - 1);
                                            this.getModel().setValue("hc95_cost_item_en", addRow, newRowIndex);
                                        }

                                    }
                                }
                            }
                        }
                        entryentityColl = this.getModel().getEntryEntity("hc95_tree_entryentity");
                        this.getModel().updateEntryCache(entryentityColl);
                    }
                }
            }
        }
        super.closedCallBack(closedCallBackEvent);
    }

    public void iterationCostType(DynamicObject costTypeRowObject, List<DynamicObject> allTreeCostType) {
        if (costTypeRowObject != null) {
            Object pk = costTypeRowObject.getPkValue();
            boolean present = allTreeCostType.stream().filter(f1 -> f1.getPkValue().equals(pk)).findFirst().isPresent();
            if (!present) {
                allTreeCostType.add(costTypeRowObject);
            }
            DynamicObject parent = costTypeRowObject.getDynamicObject("parent");
            if (parent != null) {
                DynamicObject costTypeRowObjectParent = BusinessDataServiceHelperExt.loadSingle(parent.getPkValue(), "hc95_costtype_tree");
                iterationCostType(costTypeRowObjectParent, allTreeCostType);
            }
        }
    }

    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {
        EntryProp entryProp = e.getEntryProp();
        String entryPropName = entryProp.getName();
        super.afterDeleteRow(e);
        if ("hc95_tree_entryentity".equals(entryPropName)) {
            filedUpdateIsLeaf();
            handLeafAdd();
            filedLock();
            treeSum();
            handLeafAdd();
            onlyFiledLock();
            handleSumRow();
        }
    }

    public void handLeafAdd() {
        DynamicObject targetCost = BusinessDataServiceHelper.loadSingle(this.getModel().getValue("hc95_mbcbd_id"), "hc95_target_cost");
        DynamicObjectCollection entryentityOld = targetCost.getDynamicObjectCollection("hc95_tree_entryentity");
        List<DynamicObject> leafColl = entryentityOld.stream().filter(f1 -> f1.getBoolean("hc95_is_leaf")).collect(Collectors.toList());
        if (leafColl != null && leafColl.size() >= 1) {
            DynamicObjectCollection entryentity = this.getModel().getEntryEntity("hc95_tree_entryentity");
            for (DynamicObject leafRow : leafColl) {
                String leafId = leafRow.getString("id");
                Optional<DynamicObject> hc95_oldmbcbmx_id = entryentity.stream().filter(f1 -> f1.getString("hc95_oldmbcbmx_id").equals(leafId)).findFirst();
                if (hc95_oldmbcbmx_id.isPresent()) {
                    String leafRowLongId = hc95_oldmbcbmx_id.get().getString("hc95_longid_en");
                    int seqLeaf = hc95_oldmbcbmx_id.get().getInt("seq") - 1;
                    //判断是否有下级
                    List<DynamicObject> childLevel = entryentity.stream().filter(f1 -> f1.getString("hc95_longid_en").startsWith(leafRowLongId + ".") && f1.getBoolean("hc95_is_leaf")).collect(Collectors.toList());
                    if (childLevel != null && childLevel.size() >= 1) {
                        //先清空
                        for (int i = 0; i < childLevel.size(); i++) {
                            DynamicObject childLevelRow = childLevel.get(i);
                            int seq = childLevelRow.getInt("seq") - 1;
                            if (i == 0) {
                                //第一行
                                //原值
                                BigDecimal hc95_qty_sum_en = Convert.toBigDecimal(this.getModel().getValue("hc95_qty_sum_en", seq));
                                BigDecimal hc95_ysmucbe_sum_en = Convert.toBigDecimal(this.getModel().getValue("hc95_ysmucbe_sum_en", seq));
                                if (hc95_qty_sum_en.compareTo(BigDecimal.ZERO) == 0 || hc95_ysmucbe_sum_en.compareTo(BigDecimal.ZERO) == 0) {
                                    this.getModel().setValue("hc95_price_en", leafRow.get("hc95_price_en"), seq);
                                    this.getModel().setValue("hc95_qty_sum_en", leafRow.get("hc95_qty_sum_en"), seq);
                                    this.getModel().setValue("hc95_sl_sum_en", leafRow.get("hc95_sl_sum_en"), seq);
                                    this.getModel().setValue("hc95_se_sum_en", leafRow.get("hc95_se_sum_en"), seq);
                                    this.getModel().setValue("hc95_ysmucbe_sum_en", leafRow.get("hc95_zxmucbe_sum_en"), seq);
                                }

                                //新值
                                BigDecimal hc95_qty_sum_en_x = Convert.toBigDecimal(this.getModel().getValue("hc95_qty_sum_en_x", seq));
                                BigDecimal hc95_zxmucbe_sum_en = Convert.toBigDecimal(this.getModel().getValue("hc95_zxmucbe_sum_en", seq));
                                if (hc95_qty_sum_en_x.compareTo(BigDecimal.ZERO) == 0 || hc95_zxmucbe_sum_en.compareTo(BigDecimal.ZERO) == 0) {
                                    this.getModel().setValue("hc95_price_en_x", leafRow.get("hc95_price_en"), seq);
                                    this.getModel().setValue("hc95_qty_sum_en_x", leafRow.get("hc95_qty_sum_en"), seq);
                                    this.getModel().setValue("hc95_sl_sum_en_x", leafRow.get("hc95_sl_sum_en"), seq);
                                    this.getModel().setValue("hc95_se_sum_en_x", leafRow.get("hc95_se_sum_en"), seq);
                                    this.getModel().setValue("hc95_zxmucbe_sum_en", leafRow.get("hc95_zxmucbe_sum_en"), seq);
                                }
                                hc95_zxmucbe_sum_en = Convert.toBigDecimal(this.getModel().getValue("hc95_zxmucbe_sum_en", seq));
                                hc95_ysmucbe_sum_en = Convert.toBigDecimal(this.getModel().getValue("hc95_ysmucbe_sum_en", seq));

                                this.getModel().setValue("hc95_change_amount_en", hc95_zxmucbe_sum_en.subtract(hc95_ysmucbe_sum_en), seq);
                            } else {
                                this.getModel().setValue("hc95_price_en", null, seq);
                                this.getModel().setValue("hc95_qty_sum_en", null, seq);
                                this.getModel().setValue("hc95_sl_sum_en", null, seq);
                                this.getModel().setValue("hc95_se_sum_en", null, seq);
                                this.getModel().setValue("hc95_ysmucbe_sum_en", null, seq);
                            }
                        }
                    } else {
                        //原值
                        this.getModel().setValue("hc95_accoun_en", leafRow.get("hc95_accoun_en"), seqLeaf);
                        this.getModel().setValue("hc95_unit_en", leafRow.get("hc95_unit_en"), seqLeaf);
                        this.getModel().setValue("hc95_price_en", leafRow.get("hc95_price_en"), seqLeaf);
                        this.getModel().setValue("hc95_qty_sum_en", leafRow.get("hc95_qty_sum_en"), seqLeaf);
                        this.getModel().setValue("hc95_sl_sum_en", leafRow.get("hc95_sl_sum_en"), seqLeaf);
                        this.getModel().setValue("hc95_se_sum_en", leafRow.get("hc95_se_sum_en"), seqLeaf);
                        this.getModel().setValue("hc95_ysmucbe_sum_en", leafRow.get("hc95_zxmucbe_sum_en"), seqLeaf);

                        //新值
                        this.getModel().setValue("hc95_price_en_x", leafRow.get("hc95_price_en"), seqLeaf);
                        this.getModel().setValue("hc95_qty_sum_en_x", leafRow.get("hc95_qty_sum_en"), seqLeaf);
                        this.getModel().setValue("hc95_sl_sum_en_x", leafRow.get("hc95_sl_sum_en"), seqLeaf);
                        this.getModel().setValue("hc95_se_sum_en_x", leafRow.get("hc95_se_sum_en"), seqLeaf);
                        this.getModel().setValue("hc95_zxmucbe_sum_en", leafRow.get("hc95_zxmucbe_sum_en"), seqLeaf);

                        this.getModel().setValue("hc95_change_amount_en", BigDecimal.ZERO, seqLeaf);
                    }
                }
            }
        }
    }

    public void treeSum() {
        DynamicObjectCollection targetCost = this.getModel().getEntryEntity("hc95_tree_entryentity");
        if (targetCost != null && targetCost.size() >= 1) {
            List<Integer> rankEns = targetCost.stream().map(i1 -> i1.getInt("hc95_rank_en")).collect(Collectors.toList());
            Integer rankEnMax = Collections.max(rankEns);
            treeSumByIds(targetCost, rankEnMax);
        }
    }

    public void treeSumByIds(DynamicObjectCollection targetCost, Integer rankEnMax) {
        if (rankEnMax <= 0) {
            return;
        }
        String rankEnMaxStr = String.valueOf(rankEnMax);
        targetCost = this.getModel().getEntryEntity("hc95_tree_entryentity");
        Map<String, List<DynamicObject>> parentGroup = targetCost.stream().filter(f1 -> rankEnMaxStr.equals(f1.getString("hc95_rank_en"))).collect(Collectors.groupingBy(x -> x.getString("pid")));
        for (String pid : parentGroup.keySet()) {
            if ("0".equals(pid)) {
                continue;
            }
            List<DynamicObject> dynamicObjects = parentGroup.get(pid);
            //汇总 最新目标成本额和税额
            BigDecimal hc95_zxmucbe_sum_en = dynamicObjects.stream().map(m1 -> m1.getBigDecimal("hc95_zxmucbe_sum_en")).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal hc95_se_sum_en_x = dynamicObjects.stream().map(m1 -> m1.getBigDecimal("hc95_se_sum_en_x")).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal hc95_change_amount_en = dynamicObjects.stream().map(m1 -> m1.getBigDecimal("hc95_change_amount_en")).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal hc95_ysmucbe_sum_en = dynamicObjects.stream().map(m1 -> m1.getBigDecimal("hc95_ysmucbe_sum_en")).reduce(BigDecimal.ZERO, BigDecimal::add);
            DynamicObject parentRow = targetCost.stream().filter(f1 -> f1.getString("id").equals(pid)).findFirst().get();
            int seq = parentRow.getInt("seq") - 1;
            parentRow.set("hc95_zxmucbe_sum_en", hc95_zxmucbe_sum_en);
            parentRow.set("hc95_se_sum_en_x", hc95_se_sum_en_x);
            parentRow.set("hc95_change_amount_en", hc95_change_amount_en);
            parentRow.set("hc95_ysmucbe_sum_en", hc95_ysmucbe_sum_en);
            this.getView().updateView("hc95_zxmucbe_sum_en", seq);
            this.getView().updateView("hc95_ysmucbe_sum_en", seq);
            this.getView().updateView("hc95_se_sum_en_x", seq);
            this.getView().updateView("hc95_change_amount_en", seq);
        }
        rankEnMax = rankEnMax - 1;
        treeSumByIds(targetCost, rankEnMax);
    }

    public void onlyFiledLock() {
        DynamicObjectCollection targetCost = this.getModel().getEntryEntity("hc95_tree_entryentity");
        if (targetCost != null && targetCost.size() >= 1) {
            //先全部锁定
            for (int i = 0; i < targetCost.size(); i++) {
                DynamicObject targetCostRow = targetCost.get(i);
                String id = targetCostRow.getString("id");
                //判断本级id是否是别人的父级id
                List<DynamicObject> subColl = targetCost.stream().filter(f1 -> f1.getString("pid").equals(id)).collect(Collectors.toList());
                if (subColl != null && subColl.size() >= 1) {
                    //有子级
                    this.getView().setEnable(false, i, "hc95_accoun_en");
                    this.getView().setEnable(false, i, "hc95_price_en_x");
                    this.getView().setEnable(false, i, "hc95_unit_en");
                    this.getView().setEnable(false, i, "hc95_qty_sum_en_x");
                    this.getView().setEnable(false, i, "hc95_sl_sum_en_x");
                } else {
                    this.getView().setEnable(true, i, "hc95_accoun_en");
                    this.getView().setEnable(true, i, "hc95_price_en_x");
                    this.getView().setEnable(true, i, "hc95_unit_en");
                    this.getView().setEnable(true, i, "hc95_qty_sum_en_x");
                    this.getView().setEnable(true, i, "hc95_sl_sum_en_x");
                }
            }
        }
    }


    public void filedUpdateIsLeaf() {
        DynamicObjectCollection targetCost = this.getModel().getEntryEntity("hc95_tree_entryentity");
        if (targetCost != null && targetCost.size() >= 1) {
            for (int i = 0; i < targetCost.size(); i++) {
                DynamicObject targetCostRow = targetCost.get(i);
                String id = targetCostRow.getString("id");
                List<DynamicObject> subColl = targetCost.stream().filter(f1 -> f1.getString("pid").equals(id)).collect(Collectors.toList());
                if (subColl != null && subColl.size() >= 1) {
                    this.getModel().setValue("hc95_is_leaf", false, i);
                    this.getView().updateView("hc95_is_leaf", i);

                } else {
                    this.getModel().setValue("hc95_is_leaf", true, i);
                    this.getView().updateView("hc95_is_leaf", i);

                }
            }
        }
    }


    public void filedLock() {
        DynamicObjectCollection targetCost = this.getModel().getEntryEntity("hc95_tree_entryentity");
        if (targetCost != null && targetCost.size() >= 1) {
            //先全部锁定
            for (int i = 0; i < targetCost.size(); i++) {
                DynamicObject targetCostRow = targetCost.get(i);
                String id = targetCostRow.getString("id");
                BigDecimal hc95_price_en_x = targetCostRow.getBigDecimal("hc95_price_en_x");
                BigDecimal hc95_qty_sum_en_x = targetCostRow.getBigDecimal("hc95_qty_sum_en_x");
                List<DynamicObject> subColl = targetCost.stream().filter(f1 -> f1.getString("pid").equals(id)).collect(Collectors.toList());
                if (subColl != null && subColl.size() >= 1) {

                    this.getView().setEnable(false, i, "hc95_accoun_en");
                    this.getView().setEnable(false, i, "hc95_price_en_x");
                    this.getView().setEnable(false, i, "hc95_unit_en");
                    this.getView().setEnable(false, i, "hc95_qty_sum_en_x");
                    this.getView().setEnable(false, i, "hc95_sl_sum_en_x");

                    this.getModel().setValue("hc95_accoun_en", null, i);
                    this.getModel().setValue("hc95_price_en_x", null, i);
                    this.getModel().setValue("hc95_unit_en", null, i);
                    this.getModel().setValue("hc95_qty_sum_en_x", null, i);
                    this.getModel().setValue("hc95_sl_sum_en_x", null, i);
                    this.getModel().setValue("hc95_se_sum_en_x", null, i);
                    this.getModel().setValue("hc95_yyjezc_sum_en", null, i);
                    this.getModel().setValue("hc95_yyjeht_sum_en", null, i);
                    this.getModel().setValue("hc95_kymuebe_sum_en", null, i);
                    this.getModel().setValue("hc95_change_amount_en", null, i);
                    this.getModel().setValue("hc95_is_leaf", false, i);

                    this.getModel().setValue("hc95_price_en", null, i);
                    this.getModel().setValue("hc95_qty_sum_en", null, i);
                    this.getModel().setValue("hc95_sl_sum_en", null, i);
                    this.getModel().setValue("hc95_se_sum_en", null, i);

                    this.getView().updateView("hc95_change_amount_en", i);
                    this.getView().updateView("hc95_price_en", i);
                    this.getView().updateView("hc95_qty_sum_en", i);
                    this.getView().updateView("hc95_sl_sum_en", i);
                    this.getView().updateView("hc95_se_sum_en", i);
                    this.getView().updateView("hc95_accoun_en", i);
                    this.getView().updateView("hc95_price_en_x", i);
                    this.getView().updateView("hc95_unit_en", i);
                    this.getView().updateView("hc95_qty_sum_en_x", i);
                    this.getView().updateView("hc95_sl_sum_en_x", i);
                    this.getView().updateView("hc95_se_sum_en_x", i);
                    this.getView().updateView("hc95_yyjezc_sum_en", i);
                    this.getView().updateView("hc95_yyjeht_sum_en", i);
                    this.getView().updateView("hc95_kymuebe_sum_en", i);
                    this.getView().updateView("hc95_is_leaf", i);

                } else {
                    this.getView().setEnable(true, i, "hc95_accoun_en");
                    this.getView().setEnable(true, i, "hc95_price_en_x");
                    this.getView().setEnable(true, i, "hc95_unit_en");
                    this.getView().setEnable(true, i, "hc95_qty_sum_en_x");
                    this.getView().setEnable(true, i, "hc95_sl_sum_en_x");
                    this.getModel().setValue("hc95_is_leaf", true, i);
                    if ((hc95_qty_sum_en_x == null || 0 == BigDecimal.ZERO.compareTo(hc95_qty_sum_en_x)) && (hc95_price_en_x == null || 0 == BigDecimal.ZERO.compareTo(hc95_price_en_x))) {
                        this.getModel().setValue("hc95_zxmucbe_sum_en", null, i);
                        this.getModel().setValue("hc95_se_sum_en_x", null, i);
                    }

                    this.getView().updateView("hc95_is_leaf", i);
                    this.getView().updateView("hc95_zxmucbe_sum_en", i);
                    this.getView().updateView("hc95_se_sum_en_x", i);

                }
            }
        }
    }

    public void handleSumRow() {
        EntryGrid grid = this.getView().getControl("hc95_tree_entryentity");
        Map<String, String> map = new HashMap<>();
        DynamicObjectCollection targetCost = this.getModel().getEntryEntity("hc95_tree_entryentity");
        if (targetCost != null && targetCost.size() >= 1) {
            BigDecimal hc95_zxmucbe_sum_en = targetCost.stream().filter(f1 -> f1.getBoolean("hc95_is_leaf")).map(m1 -> m1.getBigDecimal("hc95_zxmucbe_sum_en")).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal hc95_se_sum_en = targetCost.stream().filter(f1 -> f1.getBoolean("hc95_is_leaf")).map(m1 -> m1.getBigDecimal("hc95_se_sum_en")).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal hc95_ysmucbe_sum_en = targetCost.stream().filter(f1 -> f1.getBoolean("hc95_is_leaf")).map(m1 -> m1.getBigDecimal("hc95_ysmucbe_sum_en")).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal hc95_se_sum_en_x = targetCost.stream().filter(f1 -> f1.getBoolean("hc95_is_leaf")).map(m1 -> m1.getBigDecimal("hc95_se_sum_en_x")).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal hc95_change_amount_en = targetCost.stream().filter(f1 -> f1.getBoolean("hc95_is_leaf")).map(m1 -> m1.getBigDecimal("hc95_change_amount_en")).reduce(BigDecimal.ZERO, BigDecimal::add);
            map.put("hc95_zxmucbe_sum_en", hc95_zxmucbe_sum_en.toPlainString());
            map.put("hc95_se_sum_en", hc95_se_sum_en.toPlainString());
            map.put("hc95_ysmucbe_sum_en", hc95_ysmucbe_sum_en.toPlainString());
            map.put("hc95_se_sum_en_x", hc95_se_sum_en_x.toPlainString());
            map.put("hc95_change_amount_en", hc95_change_amount_en.toPlainString());
            grid.setFloatButtomData(map);
            this.getModel().setValue("hc95_change_amount", hc95_change_amount_en);
        } else {
            map.put("hc95_zxmucbe_sum_en", "");
            map.put("hc95_se_sum_en", "");
            map.put("hc95_ysmucbe_sum_en", "");
            map.put("hc95_se_sum_en_x", "");
            map.put("hc95_change_amount_en", "");
            this.getModel().setValue("hc95_change_amount_en", BigDecimal.ZERO);
            grid.setFloatButtomData(map);
        }
    }

    public void handVersionField() {
        DynamicObject ecProject = (DynamicObject) this.getModel().getValue("hc95_project_number");
        String hc95_version = this.getModel().getValue("hc95_version").toString();
        this.getModel().setValue("billno", ecProject.getString("number") + "_" + hc95_version);
        this.getModel().setValue("hc95_version_new", hc95_version);
        this.getModel().setValue("hc95_newversion_number", this.getModel().getValue("hc95_version_number"));
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String propName = e.getProperty().getName();
        if ("hc95_cost_item_en".equals(propName)) {//目标成本项
            DynamicObject oldValue = (DynamicObject) e.getChangeSet()[0].getOldValue();
            DynamicObject newValue = (DynamicObject) e.getChangeSet()[0].getNewValue();
            if (oldValue != newValue) {
                int rowIndex = e.getChangeSet()[0].getRowIndex();
                DynamicObjectCollection entryentity = this.getModel().getEntryEntity("hc95_tree_entryentity");
                if (entryentity != null) {
                    DynamicObject rowCurrent = entryentity.get(rowIndex);
                    String hc95_longid_en = rowCurrent.getString("hc95_longid_en");
                    List<DynamicObject> collChilde = entryentity.stream().filter(f1 -> f1.getString("hc95_longid_en").startsWith(hc95_longid_en + ".")).collect(Collectors.toList());
                    collChilde.forEach(item -> {
                        item.set("hc95_cost_item_en", null);
                        int seq = item.getInt("seq") - 1;
                        this.getView().updateView("hc95_cost_item_en", seq);
                    });
                }

            }
        }
        if ("hc95_adjust_type".equals(propName)) {
            Object adjustType = e.getChangeSet()[0].getNewValue();
            BigDecimal versionNumberOld = (BigDecimal) this.getModel().getValue("hc95_version_number");
            String versionOldStr = this.getModel().getValue("hc95_version").toString();
            BigDecimal versionNumberNew = new BigDecimal(versionNumberOld.toPlainString());
            String versionNewStr = versionOldStr;
            if (adjustType != null) {
                DynamicObject ecProject = (DynamicObject) this.getModel().getValue("hc95_project_number");
                String adjustTypeStr = adjustType.toString();
                if ("1".equals(adjustTypeStr)) {//动态成本调整
                    versionNumberNew = versionNumberNew.add(new BigDecimal("0.1"));
                    this.getModel().setValue("hc95_newversion_number", versionNumberNew);
                    versionNewStr = versionOldStr.substring(0, 3) + "V" + versionNumberNew.toPlainString();
                    this.getModel().setValue("hc95_version_new", versionNewStr);
                    this.getModel().setValue("billno", ecProject.getString("number") + "_" + versionNewStr);
                } else if ("2".equals(adjustTypeStr)) {//目标成本升级 这个升级后就是施工版

                    versionNumberNew = versionNumberNew.add(new BigDecimal("1"));
                    if (versionOldStr != null && versionOldStr.startsWith("启动版")) {
                        versionNumberNew = new BigDecimal("1.0");
                    }
                    this.getModel().setValue("hc95_newversion_number", versionNumberNew);
                    versionNewStr = "施工版V" + versionNumberNew.toPlainString();
                    this.getModel().setValue("hc95_version_new", versionNewStr);
                    this.getModel().setValue("billno", ecProject.getString("number") + "_" + versionNewStr);
                } else {
                    handVersionField();
                }
            } else {
                handVersionField();
            }
        } else if ("hc95_qty_sum_en_x".equals(propName) || "hc95_price_en_x".equals(propName) || "hc95_sl_sum_en_x".equals(propName)) {
            treeSum();
            onlyFiledLock();
            handleSumRow();
        }
    }


}